/*
 * ============================================================================
 *
 *       Filename:  http.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/26/2018 05:39:55 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <ev.h>

#include "http.h"

size_t just_return( char *ptr, size_t size, size_t  nmemb,  void *userdata)
{
	return size * nmemb;
}

int  http_send(char *url, char *data, void *callback, struct curl_slist * headers)
{
	int retval = 0;
	if(callback == NULL)
		callback = just_return;

	CURL *handle;
	handle = curl_easy_init();
	if(handle == NULL) {
		fprintf(stderr, "Init curl failed:%m\n");
		exit(-1);
	}

	CURLcode ret;

	/* http headers */
	if(headers) {
		ret = curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set httpheader option failed:%m\n");
			exit(-1);
		}
	}
	/* set post data */
	if(data) {
		/* set post */
		ret = curl_easy_setopt(handle, CURLOPT_POST, 1);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set post option failed:%m\n");
			exit(-1);
		}

		ret = curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set post data option failed:%m\n");
			exit(-1);
		}
	}

	if(callback != NULL) {
		/* set ret_call */
		ret = curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, callback);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set post data option failed:%m\n");
			exit(-1);
		}
	}

	ret = curl_easy_setopt(handle, CURLOPT_URL, url);
	if(ret != CURLE_OK) {
		fprintf(stderr, "set url option failed:%m\n");
		exit(-1);
	}

	ret = curl_easy_perform(handle);
	if(ret != CURLE_OK) {
		fprintf(stderr, "curl perform failed:%s\n", url);
		retval = -1;
		goto end;
	}
	fprintf(stderr, "curl perform success:%s\n", url);

end:
	curl_easy_cleanup(handle);
	if(headers)
		curl_slist_free_all(headers);
	return retval;
}

/* Die if we get a bad CURLMcode somewhere */
static void mcode_or_die(const char *where, CURLMcode code)
{
	if(CURLM_OK != code) {
		const char *s;
		switch(code) {
		case CURLM_BAD_HANDLE:
			s = "CURLM_BAD_HANDLE";
			break;
		case CURLM_BAD_EASY_HANDLE:
			s = "CURLM_BAD_EASY_HANDLE";
			break;
		case CURLM_OUT_OF_MEMORY:
			s = "CURLM_OUT_OF_MEMORY";
			break;
		case CURLM_INTERNAL_ERROR:
			s = "CURLM_INTERNAL_ERROR";
			break;
		case CURLM_UNKNOWN_OPTION:
			s = "CURLM_UNKNOWN_OPTION";
			break;
		case CURLM_LAST:
			s = "CURLM_LAST";
			break;
		default:
			s = "CURLM_unknown";
			break;
		case CURLM_BAD_SOCKET:
			s = "CURLM_BAD_SOCKET";
			fprintf(stderr, "ERROR: %s returns %s\n", where, s);
			/* ignore this error */
			return;
		}
		fprintf(stderr, "ERROR: %s returns %s\n", where, s);
		exit(code);
	}
}


/* Check for completed transfers, and remove their easy handles */
static void check_multi_info(GlobalInfo *g)
{
	char *eff_url;
	CURLMsg *msg;
	int msgs_left;
	ConnInfo *conn;
	CURL *easy;
	CURLcode res;

	while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
		if(msg->msg == CURLMSG_DONE) {
			easy = msg->easy_handle;
			res = msg->data.result;
			curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
			curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
			printf("DONE: %s => (%d) %s\n", eff_url, res, conn->error);
			curl_multi_remove_handle(g->multi, easy);
			free(conn->url);
			free(conn->data);
			if(conn->recvcb)
				conn->recvcb(conn->recv);

			curl_easy_cleanup(easy);
			free(conn);
		}
	}
}

/* Called by libevent when our timeout expires */
static void timer_cb(EV_P_ struct ev_timer *w, int revents)
{
	GlobalInfo *g = (GlobalInfo *)w->data;
	CURLMcode rc;

	rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0,
		&g->still_running);
	mcode_or_die("timer_cb: curl_multi_socket_action", rc);
	check_multi_info(g);
}

/* Update the event timer after curl_multi library calls */
static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
{
	ev_timer_stop(g->loop, &g->timer_event);
	if(timeout_ms > 0) {
		double  t = timeout_ms / 1000;
		ev_timer_init(&g->timer_event, timer_cb, t, 0.);
		ev_timer_start(g->loop, &g->timer_event);
	} else if(timeout_ms == 0) {
		timer_cb(g->loop, &g->timer_event, 0);
	}
	return 0;
}

/* Clean up the SockInfo structure */
static void remsock(SockInfo *f, GlobalInfo *g)
{
	if(f) {
		if(f->evset)
			ev_io_stop(g->loop, &f->ev);
		free(f);
	}
}

/* Called by libevent when we get action on a multi socket */
static void event_cb(EV_P_ struct ev_io *w, int revents)
{
	GlobalInfo *g = (GlobalInfo*) w->data;
	CURLMcode rc;

	int action = (revents&EV_READ?CURL_POLL_IN:0)|
		(revents&EV_WRITE?CURL_POLL_OUT:0);
	rc = curl_multi_socket_action(g->multi, w->fd, action, &g->still_running);
	mcode_or_die("event_cb: curl_multi_socket_action", rc);
	check_multi_info(g);
	if(g->still_running <= 0)
		ev_timer_stop(g->loop, &g->timer_event);
}

/* Assign information to a SockInfo structure */
static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
	GlobalInfo *g)
{
	int kind = (act&CURL_POLL_IN?EV_READ:0)|(act&CURL_POLL_OUT?EV_WRITE:0);

	f->sockfd = s;
	f->action = act;
	f->easy = e;
	if(f->evset)
		ev_io_stop(g->loop, &f->ev);
	ev_io_init(&f->ev, event_cb, f->sockfd, kind);
	f->ev.data = g;
	f->evset = 1;
	ev_io_start(g->loop, &f->ev);
}

/* Initialize a new SockInfo structure */
static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
{
	SockInfo *fdp = ss_malloc(sizeof(SockInfo));

	fdp->global = g;
	setsock(fdp, s, easy, action, g);
	curl_multi_assign(g->multi, s, fdp);
}

static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
{
	GlobalInfo *g = (GlobalInfo*) cbp;
	SockInfo *fdp = (SockInfo*) sockp;
	const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE"};

	fprintf(stderr, "socket callback: s=%d e=%p what=%s ",
		s, e, whatstr[what]);
	if(what == CURL_POLL_REMOVE) {
		remsock(fdp, g);
	} else {
		if(!fdp) {
			fprintf(stderr, "Adding data: %s\n", whatstr[what]);
			addsock(s, e, what, g);
		} else {
			fprintf(stderr, "Changing action from %s to %s\n",
				whatstr[fdp->action], whatstr[what]);
			setsock(fdp, s, e, what, g);
		}
	}
	return 0;
}

GlobalInfo *http_multi_init(EV_P)
{
	GlobalInfo *g = ss_malloc(sizeof(GlobalInfo));
	g->loop = EV_A;
	g->multi = curl_multi_init();
	ev_timer_init(&g->timer_event, timer_cb, 0., 0.);
	g->timer_event.data = g;
	curl_multi_setopt(g->multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
	curl_multi_setopt(g->multi, CURLMOPT_SOCKETDATA, g);
	curl_multi_setopt(g->multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
	curl_multi_setopt(g->multi, CURLMOPT_TIMERDATA, g);
	return g;
}

void http_multi_clean(GlobalInfo *g)
{
	curl_multi_cleanup(g->multi);
}

void http_multi_send(GlobalInfo *g, char *url, char *data, void *callback,
	void *recv, recvcb cb)
{
	int ret;
	ConnInfo *conn;
	CURLMcode rc;

	conn = ss_malloc(sizeof(ConnInfo));
	conn->easy = curl_easy_init();
	if(!conn->easy) {
		fprintf(stderr, "curl_easy_init() failed, exiting!\n");
		return;
	}
	conn->global = g;
	conn->recv = recv;
	conn->recvcb = cb;
	conn->url = strdup(url);
	conn->data = strdup(data);
	curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
	/* set post data */
	if(conn->data) {
		/* set post */
		ret = curl_easy_setopt(conn->easy, CURLOPT_POST, 1);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set post option failed:%m\n");
			exit(-1);
		}

		ret = curl_easy_setopt(conn->easy, CURLOPT_POSTFIELDS, conn->data);
		if(ret != CURLE_OK) {
			fprintf(stderr, "set post data option failed:%m\n");
			exit(-1);
		}
	}

	if(!callback)
		callback = just_return;
	curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, callback);
	curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
	curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
	curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
	curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
	curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);

	rc = curl_multi_add_handle(g->multi, conn->easy);
	mcode_or_die("new_conn: curl_multi_add_handle", rc);
	/* note that the add_handle() will set a time-out to trigger very soon so
	   that the necessary socket_action() call will be called by this app */
}
